package com.qdsg.ysg.doctor.ui.activity.prescription;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.eventbus.PrescriptionAchieveEvent;
import com.qdsg.ysg.doctor.ui.activity.checkout.MedicalSkillsBillingActivity;
import com.qdsg.ysg.doctor.ui.adapter.SecondAdapter;
import com.qdsg.ysg.doctor.ui.dialog.Item2Dialog;
import com.qdsg.ysg.doctor.ui.dialog.ItemDialog;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.PrescriptionResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilList;

/**
 * 写病历
 * Created by lbj on 2021/8/9 9:53
 * @author DELL
 */
public class AddCaseActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.edt_state)
    EditText edtState;
    @BindView(R.id.btn_yes)
    RadioButton btnYes;
    @BindView(R.id.btn_no)
    RadioButton btnNo;
    @BindView(R.id.edt_past)
    EditText edtPast;
    @BindView(R.id.edt_xbs)
    EditText edtXbs;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.edt_dept)
    EditText edtDept;
    @BindView(R.id.tv_prefix)
    TextView tvPrefix;
    @BindView(R.id.tv_middle)
    TextView tvMiddle;
    @BindView(R.id.tv_suffix)
    TextView tvSuffix;
    @BindView(R.id.iv_second_add)
    ImageView ivSecondAdd;
    @BindView(R.id.second_recyclerView)
    RecyclerView secondRecyclerView;
    @BindView(R.id.edt_advice)
    EditText edtAdvice;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_billing)
    TextView tvBilling;

    SecondAdapter secondAdapter;
    List<PrescriptionResponse.Prescription> list = new ArrayList<>();
    List<PrescriptionResponse.Second> list2 = new ArrayList<>();

    String medicalId, preAppendId, icdId, tailAppendId, diagnoseId, patientId, oneselfState;
    Boolean isGuoYao = false, isCanNext = false;

    public static final int CODE_REQUEST_PRESCRIBE = 10000;
    public static final int CODE_REQUEST_BILLING = 10001;

    @Override
    protected void initViews() {
        EventBus.getDefault().register(this);
        tvTitle.setText("写病历");
        edtState.setText(oneselfState);
        LinearLayoutManager manager2 = new LinearLayoutManager(this);
        manager2.setOrientation(LinearLayoutManager.VERTICAL);
        secondRecyclerView.setLayoutManager(manager2);
        secondAdapter = new SecondAdapter(this, list2, true, isGuoYao);
        secondRecyclerView.setAdapter(secondAdapter);

        btnYes.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                edtPast.setVisibility(View.VISIBLE);
            } else {
                edtPast.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void initData() {
        diagnoseId = getIntent().getStringExtra("diagnoseId");
        patientId = getIntent().getStringExtra("patientId");
        oneselfState = getIntent().getStringExtra("oneselfState");

        if (!UtilString.isEmpty(diagnoseId)) {
            getCase();
        }
//        if (BaseApplication.caseHashMap.get( diagnoseId ) == null)
//            getCase();
//        else {
//            edtState.setText( BaseApplication.caseHashMap.get( diagnoseId ).zs );
//            edtXbs.setText( BaseApplication.caseHashMap.get( diagnoseId ).xbs );
//            edtPast.setText( BaseApplication.caseHashMap.get( diagnoseId ).jws );
//        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_add_case;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == CODE_REQUEST_PRESCRIBE || requestCode == CODE_REQUEST_BILLING) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @OnClick({R.id.tv_prefix, R.id.tv_middle, R.id.tv_suffix, R.id.iv_second_add, R.id.tv_submit, R.id.tv_next, R.id.iv_delete, R.id.tv_billing})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_prefix:
                showDialog(2, 0);
                break;
            case R.id.tv_middle:
                showSelectHeadPicDialog2();
                break;
            case R.id.tv_suffix:
                showDialog(4, 0);
                break;
            case R.id.iv_second_add: //添加次诊断
                if (UtilString.isEmpty(tvPrefix.getText().toString().trim())) {
                    ToastUtil.showToast(mContext, "请填写主诊断前缀");
                    return;
                }
                if (UtilString.isEmpty(tvMiddle.getText().toString().trim())) {
                    ToastUtil.showToast(mContext, "请填写主诊断");
                    return;
                }
                for (PrescriptionResponse.Second bean : list2) {
                    if (TextUtils.isEmpty(bean.preAppendName)) {
                        ToastUtil.showToast(mContext, "请填写次诊断前缀");
                        return;
                    } else if (TextUtils.isEmpty(bean.diagnoseName)) {
                        ToastUtil.showToast(mContext, "请填写次诊断");
                        return;
                    }
                }
//                if (UtilString.isEmpty( tvSuffix.getText().toString().trim() )) {
//                    Toast.makeText( mContext, "请填写主诊断后缀", Toast.LENGTH_SHORT ).show();
//                    return;
//                }
                list2.add(new PrescriptionResponse.Second());
                secondAdapter.notifyDataSetChanged();
                break;

            case R.id.tv_submit:
                saveCase();
                break;
            case R.id.tv_next:
                if (isCanNext) {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", diagnoseId);
                    startActivityForResult(PrescriptionListActivity.class, bundle, CODE_REQUEST_PRESCRIBE);
                } else {
                    ToastUtil.showToastCenter(mContext, "请先填写病历");
                }
                break;
            case R.id.tv_billing:
                if (isCanNext) {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", diagnoseId);
                    startActivityForResult(MedicalSkillsBillingActivity.class, bundle, CODE_REQUEST_BILLING);
                } else {
                    ToastUtil.showToastCenter(mContext, "请先填写病历");
                }
                break;
            case R.id.iv_delete:
                tvSuffix.setText("");
                tailAppendId = "";
                break;
            default:
                break;
        }
    }

    private void saveCase() {
        String zs = edtState.getText().toString().trim();
        String xbs = edtXbs.getText().toString().trim();
        String jws = edtPast.getText().toString().trim();
        String special = edtDept.getText().toString().trim();
        String diagnoseResult = edtAdvice.getText().toString().trim();
        if (UtilString.isEmpty(zs)) {
            ToastUtil.showToastCenter(mContext, "请输入主诉");
            return;
        }
        if (UtilString.isEmpty(xbs)) {
            ToastUtil.showToastCenter(mContext, "请输入现病史");
            return;
        }
        if (UtilString.isEmpty(jws) && btnYes.isChecked()) {
            ToastUtil.showToastCenter(mContext, "请输入既往史");
            return;
        }
        if (UtilString.isEmpty(tvPrefix.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请填写主诊断前缀");
            return;
        }
        if (UtilString.isEmpty(tvMiddle.getText().toString().trim())) {
            ToastUtil.showToast(mContext, "请填写主诊断");
            return;
        }
//        if (UtilString.isEmpty( tvSuffix.getText().toString().trim() )) {
//            Toast.makeText( mContext, "请填写主诊断后缀", Toast.LENGTH_SHORT ).show();
//            return;
//        }
//        if (UtilString.isEmpty( special )) {
//            ToastUtil.showToastCenter( mContext, "请输入专科检查" );
//            return;
//        }
        if (UtilString.isEmpty(diagnoseResult)) {
            ToastUtil.showToastCenter(mContext, "请输入医生意见");
            return;
        }
        List<PrescriptionResponse.Second> mListMainAndSecond = new ArrayList<>();
        mListMainAndSecond.add(new PrescriptionResponse.Second());
        mListMainAndSecond.get(0).isMain = "1";
        mListMainAndSecond.get(0).preAppendName = tvPrefix.getText().toString().trim();
        mListMainAndSecond.get(0).preAppendId = preAppendId;
        mListMainAndSecond.get(0).diagnoseName = tvMiddle.getText().toString().trim();
        mListMainAndSecond.get(0).icdId = icdId;
        mListMainAndSecond.get(0).tailAppendName = tvSuffix.getText().toString().trim();
        mListMainAndSecond.get(0).tailAppendId = tailAppendId;
        mListMainAndSecond.addAll(list2);
        showProgressDialog(mContext);
        Map<String, Object> map = new HashMap<>();
        map.put("diagnoseId", diagnoseId);
        map.put("patientId", patientId);
        map.put("zs", zs);
        map.put("xbs", xbs);
        map.put("jws", jws);
        map.put("special", special);
        map.put("diagnoseResult", diagnoseResult); //医生建议
        map.put("diagnoseDetails", mListMainAndSecond); //主次诊断信息
        if (!UtilString.isEmpty(medicalId)) {
            map.put("medicalId", medicalId);
        }

        RestProxy.getInstance().saveCase(map, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                isCanNext = true;
                //不可点击
                tvSubmit.setClickable(false);
                //或者禁用
                tvSubmit.setEnabled(false);
                tvSubmit.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_button_press));
                tvNext.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_button_unpress));
                tvBilling.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_button_unpress));
//                startActivityForResult( AddPrescriptionActivity.class, bundle, 10000 );
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                dismissProgressDialog();
            }

            @Override
            public void onComplete() {
                dismissProgressDialog();
            }
        });
    }


    public void getCase() {
        RestProxy.getInstance().getCase(diagnoseId, patientId, new Observer<PrescriptionResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(PrescriptionResponse prescriptionResponse) {
                PrescriptionResponse.MedicalConcentDTO medicalConcentDTO = prescriptionResponse.data.medicalConcentDTO;
                if (medicalConcentDTO != null) {
                    edtState.setText(medicalConcentDTO.zs);
                    edtXbs.setText(medicalConcentDTO.xbs);
                    edtPast.setText(medicalConcentDTO.jws);
                    edtDept.setText(medicalConcentDTO.special);
                    edtAdvice.setText(medicalConcentDTO.diagnoseResult);
                    medicalId = prescriptionResponse.data.medicalConcentDTO.medicalId;
                    if (!UtilString.isEmpty(medicalConcentDTO.jws)) {
                        btnYes.setChecked(true);
                    } else {
                        btnNo.setChecked(true);
                    }
                    List<PrescriptionResponse.Second> secondList = medicalConcentDTO.diagnoseDetails;
                    if (!UtilList.isEmpty(secondList)) {
                        isCanNext = true;
                        tvNext.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_button_unpress));
                        tvBilling.setBackground(ContextCompat.getDrawable(mContext, R.drawable.shape_button_unpress));
                        tvPrefix.setText(secondList.get(0).preAppendName);
                        tvMiddle.setText(secondList.get(0).diagnoseName);
                        tvSuffix.setText(secondList.get(0).tailAppendName);
                        preAppendId = secondList.get(0).preAppendId;
                        icdId = secondList.get(0).icdId;
                        tailAppendId = secondList.get(0).tailAppendId;

                        if (secondList.size() > 1) {
                            for (int i = 1; i < secondList.size(); i++) {
                                list2.add(secondList.get(i));
                            }
                            secondAdapter.notifyDataSetChanged();
                        }
                    }

                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void showDialog(final int type, final int position) {
        // 初始化点击头像弹出的对话框
        ItemDialog mItemDialog = ItemDialog.newInstance(type, "", false);
        mItemDialog.setOnItemClickListener((s, id) -> {
            if (type == 2) {
                tvPrefix.setText(s);
                preAppendId = id;
            } else if (type == 4) {
                tvSuffix.setText(s);
                tailAppendId = id;
            }
        });
        mItemDialog.show(getSupportFragmentManager(), "mItemDialog");
    }

    private void showSelectHeadPicDialog2() {
        // 初始化点击头像弹出的对话框
        Item2Dialog mItem2Dialog = Item2Dialog.newInstance(3);
        mItem2Dialog.setOnItemClickListener((s, id) -> {
            tvMiddle.setText(s);
            icdId = id;
        });
        mItem2Dialog.show(getSupportFragmentManager(), "mItemDialog");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PrescriptionAchieveEvent event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
